package com.spvs.common.core.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类
 *
 * @author supervision
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";
    public static String YYYY_MM_STR = "yyyy年MM月";

    public static String YYYY_MM_DD = "yyyy-MM-dd";
    public static String YYYY_MM_DD_STR = "yyyy年MM月dd日";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public final static String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算时间差
     *
     * @param endDate 最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    public static String dayDiff(Date startDate, Date endDate) {
        long msNum = endDate.getTime() - startDate.getTime();// 时间戳相差的毫秒数
        long dayNum = msNum / (24 * 60 * 60 * 1000);// 除以一天的毫秒数，得到相差天数
        return String.valueOf(dayNum);
    }

    public static String diffDays(Date startDate, Date endDate) {
        // 创建Calendar实例，并设置为startDate
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(startDate);
        // 设置时间部分为零
        startCal.set(Calendar.HOUR_OF_DAY, 0);
        startCal.set(Calendar.MINUTE, 0);
        startCal.set(Calendar.SECOND, 0);
        startCal.set(Calendar.MILLISECOND, 0);

        // 创建Calendar实例，并设置为endDate
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endDate);
        // 设置时间部分为零
        endCal.set(Calendar.HOUR_OF_DAY, 0);
        endCal.set(Calendar.MINUTE, 0);
        endCal.set(Calendar.SECOND, 0);
        endCal.set(Calendar.MILLISECOND, 0);

        // 获取两个日期的时间戳
        long startTime = startCal.getTimeInMillis();
        long endTime = endCal.getTimeInMillis();

        // 计算相差的天数并加1
        long dayNum = (endTime - startTime) / (24 * 60 * 60 * 1000) + 1;

        return String.valueOf(dayNum);
    }

    /**
     * 判断日期是否在范围内
     * @param targetDate 输入时间
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return
     */
    public static boolean isWithinRange(Date targetDate, Date startDate, Date endDate) {
        // 将日期转换为仅包含年月日的日期
        Date targetDateOnly = toDateOnly(targetDate);
        Date startDateOnly = toDateOnly(startDate);
        Date endDateOnly = toDateOnly(endDate);
        // 检查目标日期是否在开始日期和结束日期范围内，包括等于开始日期或结束日期的情况
        return (targetDateOnly.equals(startDateOnly) || targetDateOnly.equals(endDateOnly) ||
                (targetDateOnly.after(startDateOnly) && targetDateOnly.before(endDateOnly)));
    }
    private static Date toDateOnly(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }
    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static String dateToStringFormat(Date date,String format)
    {
        return DateFormatUtils.format(date, format);
    }

    /**
     * 获取当前时间 前N天的时间
     * @param daysBefore 天数
     * @return
     */
    public static Date getDaysBeforeToday(int daysBefore) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -daysBefore);
        return calendar.getTime();
    }

    /**
     * 将时间戳转换为指定格式的日期字符串
     *
     * @param timestamp 时间戳
     * @param format 日期格式，例如 "yyyy-MM-dd HH:mm:ss"
     * @return 格式化后的日期字符串
     */
    public static String convertTimestampToDateString(long timestamp, String format) {
        // 判断时间戳的长度
        if (String.valueOf(timestamp).length() == 10) {
            timestamp *= 1000; // 将秒级时间戳转换为毫秒级
        }

        // 创建SimpleDateFormat对象，传入格式
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        // 将时间戳转换为Date对象
        Date date = new Date(timestamp);
        // 格式化日期并返回字符串
        return sdf.format(date);
    }
}
